<?php
namespace app\api\controller;
use app\common\controller\Base;

/**
 * 定时任务
 */
class Timing extends Base{


    public function test(){
        echo '滚';
    }

    /**
     * [grade 取消会员相关操作]
     * @return [type] [description]
     */
    public function off_grade(){
        $userModel = db('user');
        $positionModel = db('user_position');

        //会员到期用户
        $list = $userModel->where('grade',1)->where('grade_end_time',['egt',strtotime(date('Y-m-d'))],['lt',strtotime(date('Y-m-d').'+1 day')])->select();

        foreach($list as $key => $val){
            //设置为普通用户
            $userModel->where('id',$val['id'])->update(['grade' => 0,'grade_end_time' => 0]);

            //删除会员最后一个非默认的地点定位
            $position_count = $positionModel->where('user_id',$val['id'])->count();
            if($position_count > $val['position_num'] + 1){

                $id = $positionModel->where('user_id',$val['id'])->where('default',0)->order('id desc')->value('id');
                $positionModel->where('id',$id)->delete();
            }
        }
    }


    /**
     * [red_back 返还红包]
     * @return [type] [description]
     */
    public function red_back(){
        $model = db('red_packet');
        $billModel = db('bill');
        $informationModel = db('information');

        $list = $model->where('pay_status',1)->where('validate_time','elt',time())->where('odd_price','gt',0)->select();
        foreach($list as $key => $val){
            $model->where('id',$val['id'])->update(['pay_status' => 2]);
            $billModel->insert([
                'user_id' => $val['user_id'],
                'user_id' => 7,
                'num' => $val['odd_price'],
                'foreign_key' => $val['id'],
                'add_time' => $val['validate_time']
            ]);

            $informationModel->insert([
                'user_id' => $val['user_id'],
                'type' => 7,
                'content' => '红包退款'.$val['odd_price'].'元',
                'add_time' => $val['validate_time']
            ]);
        }
    }
}
